#!/bin/bash

# Web3项目管理工具 - 本地开发环境脚本
# 仅启动中间件服务，前后端在IDEA中运行

set -e

echo "============================================="
echo "    Web3项目管理工具 - 本地开发环境"
echo "============================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -h, --help          显示帮助信息"
    echo "  --start             启动开发环境中间件"
    echo "  --stop              停止开发环境中间件"
    echo "  --restart           重启开发环境中间件"
    echo "  --status            查看服务状态"
    echo "  --logs              查看服务日志"
    echo "  --reset             重置开发环境（删除所有数据）"
    echo "  --db-only           仅启动MySQL数据库"
    echo "  --cache-only        仅启动Redis缓存"
    echo ""
    echo "示例:"
    echo "  $0 --start          # 启动所有中间件"
    echo "  $0 --db-only        # 仅启动数据库"
    echo "  $0 --status         # 查看服务状态"
    echo "  $0 --logs           # 查看日志"
}

# 检查Docker环境
check_docker() {
    log_step "检查Docker环境..."

    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装，请先安装Docker"
        exit 1
    fi

    if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
        log_error "Docker Compose未安装"
        exit 1
    fi

    if ! docker info &> /dev/null; then
        log_error "Docker服务未启动"
        exit 1
    fi

    log_info "Docker环境检查完成"
}

# 准备开发环境
prepare_dev_env() {
    log_step "准备开发环境..."

    # 检查配置文件
    if [ ! -f "docker-compose.local.yml" ]; then
        log_error "开发环境配置文件不存在: docker-compose.local.yml"
        exit 1
    fi

    # 创建开发环境变量文件
    if [ ! -f ".env.local" ]; then
        log_info "创建开发环境配置文件..."
        cat > .env.local << 'EOF'
# 开发环境配置
MYSQL_ROOT_PASSWORD=root123
MYSQL_USER=web3user
MYSQL_PASSWORD=web3pass

# 开发环境JWT配置
JWT_SECRET=web3-dev-jwt-secret
JWT_EXPIRATION=86400
EOF
    fi

    # 创建必要目录
    mkdir -p logs
    mkdir -p mysql/data-dev
    mkdir -p redis/data-dev

    log_info "开发环境准备完成"
}

# 启动开发环境
start_dev_services() {
    log_step "启动开发环境中间件..."

    local services=""

    case "$SERVICE_MODE" in
        "db-only")
            services="mysql-dev phpmyadmin"
            log_info "仅启动数据库服务..."
            ;;
        "cache-only")
            services="redis-dev redis-commander"
            log_info "仅启动缓存服务..."
            ;;
        *)
            services=""
            log_info "启动所有中间件服务..."
            ;;
    esac

    # 使用开发环境配置启动
    if command -v docker-compose &> /dev/null; then
        docker-compose -f docker-compose.local.yml --env-file .env.local up -d $services
    else
        docker compose -f docker-compose.local.yml --env-file .env.local up -d $services
    fi

    log_info "中间件服务启动完成"
}

# 等待服务就绪
wait_for_dev_services() {
    log_step "等待服务启动..."

    # 等待MySQL
    if docker ps | grep -q "web3-mysql-dev"; then
        log_info "等待MySQL服务..."
        for i in {1..30}; do
            if docker exec web3-mysql-dev mysqladmin ping -h localhost -u root -proot123 &> /dev/null; then
                log_info "✅ MySQL服务已就绪 (localhost:3306)"
                break
            fi
            echo -n "."
            sleep 2
        done
    fi

    # 等待Redis
    if docker ps | grep -q "web3-redis-dev"; then
        log_info "等待Redis服务..."
        for i in {1..10}; do
            if docker exec web3-redis-dev redis-cli ping &> /dev/null; then
                log_info "✅ Redis服务已就绪 (localhost:6379)"
                break
            fi
            echo -n "."
            sleep 1
        done
    fi
}

# 停止开发环境
stop_dev_services() {
    log_step "停止开发环境中间件..."

    if command -v docker-compose &> /dev/null; then
        docker-compose -f docker-compose.local.yml down
    else
        docker compose -f docker-compose.local.yml down
    fi

    log_info "开发环境已停止"
}

# 重启开发环境
restart_dev_services() {
    log_step "重启开发环境..."
    stop_dev_services
    start_dev_services
    wait_for_dev_services
    show_dev_info
}

# 重置开发环境
reset_dev_services() {
    log_step "重置开发环境..."

    read -p "⚠️  确定要重置开发环境吗？这将删除所有数据！(y/N): " confirm
    if [[ ! $confirm =~ ^[Yy]$ ]]; then
        log_info "取消重置操作"
        return
    fi

    # 停止并删除容器和数据卷
    if command -v docker-compose &> /dev/null; then
        docker-compose -f docker-compose.local.yml down -v
    else
        docker compose -f docker-compose.local.yml down -v
    fi

    # 清理开发数据
    docker volume rm web3_management_mysql_dev_data 2>/dev/null || true
    docker volume rm web3_management_redis_dev_data 2>/dev/null || true

    log_info "开发环境重置完成"
}

# 查看开发环境状态
show_dev_status() {
    log_step "开发环境状态..."

    echo ""
    echo "容器状态:"
    if command -v docker-compose &> /dev/null; then
        docker-compose -f docker-compose.local.yml ps
    else
        docker compose -f docker-compose.local.yml ps
    fi

    echo ""
    echo "服务连接测试:"

    # 检查MySQL
    if docker ps | grep -q "web3-mysql-dev"; then
        if docker exec web3-mysql-dev mysqladmin ping -h localhost -u root -proot123 &> /dev/null; then
            echo -e "  📊 MySQL:      ${GREEN}正常${NC} (localhost:3306)"
        else
            echo -e "  📊 MySQL:      ${RED}异常${NC}"
        fi
    else
        echo -e "  📊 MySQL:      ${YELLOW}未启动${NC}"
    fi

    # 检查Redis
    if docker ps | grep -q "web3-redis-dev"; then
        if docker exec web3-redis-dev redis-cli ping &> /dev/null; then
            echo -e "  🔄 Redis:      ${GREEN}正常${NC} (localhost:6379)"
        else
            echo -e "  🔄 Redis:      ${RED}异常${NC}"
        fi
    else
        echo -e "  🔄 Redis:      ${YELLOW}未启动${NC}"
    fi

    # 检查管理界面
    if docker ps | grep -q "web3-phpmyadmin"; then
        echo -e "  🎛️  PhpMyAdmin: ${GREEN}可用${NC} (http://localhost:8081)"
    fi

    if docker ps | grep -q "web3-redis-commander"; then
        echo -e "  🎛️  Redis UI:   ${GREEN}可用${NC} (http://localhost:8082)"
    fi
}

# 查看开发环境日志
show_dev_logs() {
    echo "选择要查看的服务日志:"
    echo "1) 全部服务"
    echo "2) MySQL数据库"
    echo "3) Redis缓存"
    echo "4) PhpMyAdmin"
    echo "5) Redis Commander"
    read -p "请输入选择 (1-5): " choice

    case $choice in
        1)
            if command -v docker-compose &> /dev/null; then
                docker-compose -f docker-compose.local.yml logs -f
            else
                docker compose -f docker-compose.local.yml logs -f
            fi
            ;;
        2)
            docker logs -f web3-mysql-dev
            ;;
        3)
            docker logs -f web3-redis-dev
            ;;
        4)
            docker logs -f web3-phpmyadmin
            ;;
        5)
            docker logs -f web3-redis-commander
            ;;
        *)
            log_error "无效选择"
            exit 1
            ;;
    esac
}

# 显示开发环境信息
show_dev_info() {
    echo ""
    echo "============================================="
    echo -e "${GREEN}    开发环境中间件启动完成！${NC}"
    echo "============================================="
    echo -e "📊 MySQL数据库:    ${BLUE}localhost:3306${NC}"
    echo -e "🔄 Redis缓存:      ${BLUE}localhost:6379${NC}"
    echo -e "🎛️  PhpMyAdmin:     ${BLUE}http://localhost:8081${NC}"
    echo -e "🎛️  Redis管理:      ${BLUE}http://localhost:8082${NC}"
    echo ""
    echo "数据库连接信息:"
    echo -e "  Host: ${YELLOW}localhost${NC}"
    echo -e "  Port: ${YELLOW}3306${NC}"
    echo -e "  Database: ${YELLOW}web3_management${NC}"
    echo -e "  Username: ${YELLOW}web3user${NC}"
    echo -e "  Password: ${YELLOW}web3pass${NC}"
    echo ""
    echo "Redis连接信息:"
    echo -e "  Host: ${YELLOW}localhost${NC}"
    echo -e "  Port: ${YELLOW}6379${NC}"
    echo -e "  Auth: ${YELLOW}无密码${NC}"
    echo ""
    echo "IDEA运行配置:"
    echo "  后端启动类: com.web3.management.Web3ManagementApplication"
    echo "  前端启动:   cd frontend && npm run dev"
    echo ""
    echo "管理命令:"
    echo "  查看状态: $0 --status"
    echo "  查看日志: $0 --logs"
    echo "  重启服务: $0 --restart"
    echo "  停止服务: $0 --stop"
    echo "  重置环境: $0 --reset"
    echo "============================================="
}

# 显示IDEA配置指导
show_idea_guide() {
    cat << 'EOF'

🎯 IDEA开发环境配置指导:

1. 📁 导入项目
   - 打开IDEA，选择 "Open or Import"
   - 选择 backend 目录
   - 选择 "Import project from external model" > "Maven"

2. ⚙️ 配置数据库连接
   - 打开 Database 工具窗口
   - 添加MySQL数据源:
     Host: localhost
     Port: 3306
     Database: web3_management
     User: web3user
     Password: web3pass

3. 🏃 运行后端
   - 找到 Web3ManagementApplication.java
   - 右键 > Run 'Web3ManagementApplication'
   - 访问: http://localhost:8080/actuator/health

4. 🎨 运行前端
   - 打开终端，进入 frontend 目录
   - 执行: npm install
   - 执行: npm run dev
   - 访问: http://localhost:3000

5. 🔗 API测试
   - 安装 HTTP Client 插件
   - 或使用 Postman/Apifox 测试API

EOF
}

# 主函数
main() {
    # 检查当前目录
    if [ ! -f "docker-compose.local.yml" ]; then
        log_error "请在项目根目录执行此脚本"
        exit 1
    fi

    # 解析命令行参数
    ACTION="start"
    SERVICE_MODE="all"

    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            --start)
                ACTION="start"
                shift
                ;;
            --stop)
                ACTION="stop"
                shift
                ;;
            --restart)
                ACTION="restart"
                shift
                ;;
            --status)
                ACTION="status"
                shift
                ;;
            --logs)
                ACTION="logs"
                shift
                ;;
            --reset)
                ACTION="reset"
                shift
                ;;
            --db-only)
                SERVICE_MODE="db-only"
                shift
                ;;
            --cache-only)
                SERVICE_MODE="cache-only"
                shift
                ;;
            --ide-guide)
                show_idea_guide
                exit 0
                ;;
            *)
                log_error "未知参数: $1"
                show_help
                exit 1
                ;;
        esac
    done

    # 执行对应操作
    case $ACTION in
        "start")
            check_docker
            prepare_dev_env
            start_dev_services
            wait_for_dev_services
            show_dev_info
            echo ""
            log_info "💡 运行 $0 --ide-guide 查看IDEA配置指导"
            ;;
        "stop")
            stop_dev_services
            ;;
        "restart")
            restart_dev_services
            ;;
        "status")
            show_dev_status
            ;;
        "logs")
            show_dev_logs
            ;;
        "reset")
            reset_dev_services
            ;;
        *)
            log_error "未知操作: $ACTION"
            show_help
            exit 1
            ;;
    esac
}

# 处理中断信号
trap 'echo -e "\n${YELLOW}[WARN]${NC} 操作被中断"; exit 1' INT TERM

# 执行主函数
main "$@"